package com.ipet.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ipet.system.pojo.SysRole;
import com.ipet.system.pojo.UserRole;
import com.ipet.system.service.SysRoleService;
import com.ipet.system.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/role")
@Api("角色管理")
public class RoleController {
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private UserRoleService userRoleService;
    @ApiOperation("查询所有角色")
    @GetMapping("/allRole")
    public ResponseEntity<List<SysRole>> findAll(){
        List<SysRole> list = roleService.list();
        if(CollectionUtils.isEmpty(list)){
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(list);
    }
    @ApiOperation(value = "添加或更新角色")
    @ApiImplicitParam(value = "要添加或更新的管理员角色" , name = "role" , required = true , dataType = "SysRole" , paramType = "body")
    @PostMapping("/saveOrUpdate")
    public ResponseEntity<Map<String , Object>> saveOrUpdate(@RequestBody SysRole role){
        Map map =new  HashMap<String , Object>();
        List<SysRole> roles = roleService.list(new QueryWrapper<SysRole>().eq("role_name", role.getRoleName()));
        if(roles.size() != 0){
            map.put("message" , "此角色名已存在!");
            map.put("saveOrUpdate" , false);
        }else {
            boolean saveOrUpdate = roleService.saveOrUpdate(role);
            map.put("saveOrUpdate" , saveOrUpdate);
        }

        return ResponseEntity.ok(map);
    }
    @ApiOperation(value = "删除角色")
    @ApiImplicitParam(value = "要删除的角色id" , name = "id" , required = true , dataType = "Integer" , paramType = "query")
    @DeleteMapping("/delete")
    public ResponseEntity<Boolean> delete(Integer id){
        boolean remove = roleService.removeById(id);
        if(remove){
            userRoleService.remove(new QueryWrapper<UserRole>().eq("r_id" , id));
        }
        return ResponseEntity.ok(remove);
    }
}
